package org.example.service.client;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import org.example.HelloServiceGrpc;
import org.example.helloProto;

import java.util.concurrent.TimeUnit;

/**
 * @Author : 叶荻风
 * @create : 2024/6/20 19:53
 * 异步实现
 */
public class GrpcSocketServerStreamAsync {
    public static void main(String[] args) {
        //1.创建通信的管道
        ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost",9000).usePlaintext().build();
        try{
            //2.获取代理对象stub
            HelloServiceGrpc.HelloServiceStub stub = HelloServiceGrpc.newStub(managedChannel);
            helloProto.HelloRequest.Builder builder = helloProto.HelloRequest.newBuilder();
            helloProto.HelloRequest request = builder.setUsername("difeng").build();
            //监听3个事件
            stub.c2ss(request, new StreamObserver<helloProto.HelloResponse>() {
                @Override
                public void onNext(helloProto.HelloResponse helloResponse) {
                    //服务端响应了一个消息后，需要立即处理的话，把代码写在此方法中
                    System.out.println("相应一次服务: "+helloResponse.getUsername());
                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onCompleted() {
                    //需要把服务端响应的所有数据拿到后，进行业务处理
                    System.out.println("服务结束");
                }
            });

            managedChannel.awaitTermination(15, TimeUnit.SECONDS);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            managedChannel.shutdown();
        }
    }
}
